package com.me.springcloud.feign.ssl;

import static feign.Util.ISO_8859_1;
import static feign.Util.checkNotNull;

import java.nio.charset.Charset;

import feign.RequestInterceptor;
import feign.RequestTemplate;

/**
 * An interceptor that adds the request header needed to use HTTP basic authentication.
 */
public class MyBasicAuthRequestInterceptor implements RequestInterceptor {

	private final String headerValue;

	/**
	 * Creates an interceptor that authenticates all requests with the specified username and password
	 * encoded using ISO-8859-1.
	 *
	 * @param username the username to use for authentication
	 * @param password the password to use for authentication
	 */
	public MyBasicAuthRequestInterceptor(String username, String password) {
		this(username, password, ISO_8859_1);
	}

	/**
	 * Creates an interceptor that authenticates all requests with the specified username and password
	 * encoded using the specified charset.
	 *
	 * @param username the username to use for authentication
	 * @param password the password to use for authentication
	 * @param charset the charset to use when encoding the credentials
	 */
	public MyBasicAuthRequestInterceptor(String username, String password, Charset charset) {
		checkNotNull(username, "username");
		checkNotNull(password, "password");

		this.headerValue = Bill99Util.generateAuthorization(username, password);
		// "Basic " + base64Encode((username + ":" + password).getBytes(charset));
	}

	@Override
	public void apply(RequestTemplate template) {
		template.header("Authorization", headerValue);
		template.header("Content-Type", "application/xml; charset=UTF-8");
	}

}